<?php



namespace app\api\service\grade;



use app\api\service\Basics;

use app\api\model\User as UserModel;

use app\api\model\grade\Order as OrderModel;

//use app\api\model\WxappPrepayId as WxappPrepayIdModel;

use app\api\model\user\BalanceLog as BalanceLogModel;



//use app\common\enum\OrderType as OrderTypeEnum;

use app\common\enum\order\PayType as PayTypeEnum;

use app\common\enum\user\balanceLog\Scene as SceneEnum;

use app\common\enum\grade\order\PayStatus as PayStatusEnum;

use app\common\model\user\GradeLog;



class PaySuccess extends Basics

{

    // 订单模型

    public $model;



    // 当前用户信息

    private $user;



    /**

     * 构造函数

     * PaySuccess constructor.

     * @param $orderNo

     * @throws \think\exception\DbException

     */

    public function __construct($orderNo)

    {

        // 实例化订单模型

        $this->model = OrderModel::getPayDetail($orderNo);

        $this->wxappId = $this->model['wxapp_id'];

        // 获取用户信息

        $this->user = UserModel::detail($this->model['user_id']);

    }



    /**

     * 获取订单详情

     * @return OrderModel|null

     */

    public function getOrderInfo()

    {

        return $this->model;

    }



    /**

     * 订单支付成功业务处理

     * @param int $payType 支付类型

     * @param array $payData 支付回调数据

     * @return bool

     */

    public function onPaySuccess($payType, $payData)

    {

        return $this->model->transaction(function () use ($payType, $payData) {

            // 更新订单状态

            $this->model->save([

                'pay_status' => PayStatusEnum::SUCCESS,

                'pay_time' => time(),

                'transaction_id' => $payData['transaction_id']

            ]);

            

           

            

            $log['user_id']=$this->model['user_id'];

            $log['old_grade_id']=UserModel::where(['user_id'=>$this->model['user_id']])->value('grade_id');

            $log['new_grade_id']=$this->model['grade_id'];

            $log['change_type']=20;

            $log['wxapp_id']=$this->wxappId;

            $log['create_time']=time();

            GradeLog::insert($log);



            // 更新用户等级

            $updateData['user_id']=$this->model['user_id'];

            $updateData['grade_id']=$this->model['grade_id'];

            $this->user->save($updateData);



            

            if ($payType == PayTypeEnum::WECHAT) {

//                WxappPrepayIdModel::updatePayStatus($this->model['order_id'], OrderTypeEnum::RECHARGE);

            }

            return true;

        });

    }



}